package com.gcloud.mesh.supplier.adapter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

@Slf4j
public abstract class AbstractAdapter {

	public abstract String getToken();
	
	public String get(String uri, HttpHeaders headers, String paramsStr) {
		RestTemplate restTemplate = new RestTemplate();
		String url = String.format("%s?%s", uri, paramsStr);
		HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity(headers);
		String responseBody = null;
		try {
			ResponseEntity<String> responseEntity = restTemplate
					.exchange(url, HttpMethod.GET, httpEntity, String.class);
			responseBody = responseEntity.getBody();
			log.info("AbstractAdapter responseBody:{}", responseBody);
		} catch (Exception e) {
			log.error("%s 访问异常: %s", url, e.getMessage());
		}

		return responseBody;
	};

	public String get(String url, HttpHeaders headers) {
		RestTemplate restTemplate = new RestTemplate();
		HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity(headers);
		String responseBody = null;
		try {
			ResponseEntity<String> responseEntity = restTemplate
					.exchange(url, HttpMethod.GET, httpEntity, String.class);
			responseBody = responseEntity.getBody();
		} catch (Exception e) {
			log.error("%s 访问异常: %s", url, e.getMessage());
		}

		return responseBody;
	}

	;

	public String post(String uri, HttpHeaders headers, String paramsJson) {
		RestTemplate restTemplate = new RestTemplate();
		headers.setContentType(MediaType.APPLICATION_JSON);//Content-Type
		HttpEntity<String> httpEntity = new HttpEntity<>(paramsJson, headers);
		String responseBody = null;
		try {
			ResponseEntity<String> responseEntity = restTemplate
					.exchange(uri, HttpMethod.POST, httpEntity, String.class);
			responseBody = responseEntity.getBody();
		} catch (Exception e) {
			log.error("%s 访问异常: %s", uri, e.getMessage());
		}
		return responseBody;
	}

	public String get(String uri, HttpHeaders headers, String paramsStr, SimpleClientHttpRequestFactory factory) {
		RestTemplate restTemplate = new RestTemplate(factory);
		String url = String.format("%s?%s", uri, paramsStr);
		HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity(headers);
		String responseBody = null;
		try {
			ResponseEntity<String> responseEntity = restTemplate
					.exchange(url, HttpMethod.GET, httpEntity, String.class);
			responseBody = responseEntity.getBody();
			log.info("AbstractAdapter responseBody:{}", responseBody);
		} catch (Exception e) {
			log.error("%s 访问异常: %s", url, e.getMessage());
		}

		return responseBody;
	}
}
